package com.qujia.station.controller;


import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.qujia.common.annotation.Excel;
import com.qujia.common.constant.HttpStatus;
import com.qujia.common.constant.UserConstants;
import com.qujia.common.core.controller.BaseController;
import com.qujia.common.core.domain.AjaxResult;
import com.qujia.common.core.domain.entity.SysUser;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.core.page.PageDomain;
import com.qujia.common.core.page.TableDataInfo;
import com.qujia.common.core.page.TableSupport;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.common.utils.poi.ExcelUtil;
import com.qujia.common.utils.sql.SqlUtil;
import com.qujia.station.domain.Commodity;
import com.qujia.station.domain.Enterprise;
import com.qujia.station.domain.Repositories;
import com.qujia.station.domain.Station;
import com.qujia.station.domain.dto.CommodityTemplate;
import com.qujia.station.domain.vo.CommodityExportErrorVo;
import com.qujia.station.service.CommodityService;
import com.qujia.station.service.IEnterpriseService;
import com.qujia.station.service.IStationService;
import com.qujia.station.service.RepositoryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * (Commodity)表控制层
 *
 * @author makejava
 * @since 2023-08-15 14:11:12
 */
@Api("非油品商品列表接口")
@RestController
@RequestMapping("/commodity")
@Slf4j
public class CommodityController extends BaseController {
    /**
     * 服务对象
     */
    @Resource
    private CommodityService commodityService;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private IStationService stationService;

    @Autowired
    private RepositoryService repositoryService;

    /**
     * 分页查询
     *
     * @param commodity 筛选条件
     * @return 查询结果
     */
    @PostMapping("/list")
    @ApiOperation("分页查询")
    public TableDataInfo queryByPage(@RequestBody Commodity commodity) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            commodity.setPageNum(pageNum);
            commodity.setPageSize(pageSize);
            commodity.setOrderBy(orderBy);
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        if(Objects.isNull(sysUser)){
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("请登录账号");
            rspData.setRows(null);
            rspData.setTotal(0);
            return rspData;
        }
        if(UserConstants.LEVEL_TWO.equals(sysUser.getUserLevel())){
            commodity.setEnterpriseId(sysUser.getEnterpriseId());
        } else if(UserConstants.LEVEL_THREE.equals(sysUser.getUserLevel())){
            commodity.setStationId(sysUser.getStationId());
        } else if(StringUtils.isEmpty(sysUser.getUserLevel()) || UserConstants.LEVEL_ONE.equals(sysUser.getUserLevel())) {
            Repositories repositories = new Repositories();
            List<Repositories> repositoriesList = repositoryService.selectRepositoryList(repositories);
            List<Long> stationIdList = new ArrayList<>();
            if(CollectionUtils.isNotEmpty(repositoriesList)){
                for (Repositories repository : repositoriesList) {
                    stationIdList.add(repository.getStationId());
                }
                commodity.setStationIdList(stationIdList);
            }
        } else {
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.ERROR);
            rspData.setMsg("账号无权限查看页面");
            rspData.setRows(null);
            rspData.setTotal(0);
            return rspData;
        }

        List<Commodity> list= commodityService.query(commodity);
        return getDataTable(list);
    }

    /**
     * 通过主键查询单条数据
     *
     * @param commodityId 主键
     * @return 单条数据
     */
    @GetMapping("/queryById/{commodityId}")
    @ApiOperation("通过主键查询单条数据")
    public AjaxResult queryById(@PathVariable("commodityId") Long commodityId) {
        return AjaxResult.success(commodityService.queryById(commodityId));
    }

    /**
     * 新增数据
     *
     * @param commodity 实体
     * @return 新增结果
     */
    @PostMapping("/add")
    @ApiOperation("新增数据")
    public AjaxResult add(@RequestBody Commodity commodity) {
        if(Objects.isNull(commodity) || StringUtils.isEmpty(commodity.getCommodityName())){
            return AjaxResult.error("无新增商品");
        }
        // 油企新增商品时，给所属下每个油站都新增一个商品
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser sysUser = loginUser.getUser();
        if(Objects.isNull(sysUser)){
            return AjaxResult.error("请登录账号");
        }
        if(StringUtils.isEmpty(commodity.getBarCode())){
            return AjaxResult.error("请求输入商品条形码");
        }
        if(Objects.isNull(commodity.getCategoryId())){
            return AjaxResult.error("请求填写所属分类");
        }
        if(Objects.isNull(commodity.getSupplierId())){
            return AjaxResult.error("请求填写供应商");
        }
        if(Objects.isNull(commodity.getSalePrice())){
            return AjaxResult.error("请求填写销售价格");
        }
        if(StringUtils.isEmpty(commodity.getUnit())){
            return AjaxResult.error("请求填写单位");
        }
        List<Commodity> commodityList = new ArrayList<>();
        if(UserConstants.LEVEL_TWO.equals(sysUser.getUserLevel())){
            if(Objects.isNull(commodity.getStationId()) && StringUtils.isEmpty(commodity.getIsAll())){
                return AjaxResult.error("请选择油站");
            }
            if(Objects.nonNull(commodity.getStationId())) {
                Enterprise enterprise = enterpriseService.selectEnterpriseByStationId(commodity.getStationId());
                commodity.setEnterpriseId(enterprise.getEnterpriseId());
                commodity.setEnterpriseName(enterprise.getEnterpriseName());
                Station station = stationService.selectStationById(commodity.getStationId());
                commodity.setStationId(station.getStationId());
                commodity.setStationName(station.getStationName());
                commodityList.add(commodity);
            } else if("all".equals(commodity.getIsAll())) {
                commodity.setEnterpriseId(sysUser.getEnterpriseId());
                Enterprise enterprise = enterpriseService.selectEnterpriseById(sysUser.getEnterpriseId());
                commodity.setEnterpriseName(enterprise.getEnterpriseName());
                List<Station> stationList = stationService.getStationByEnterpriseId(sysUser.getEnterpriseId());
                for (Station station : stationList) {
                    Commodity newCommodity = new Commodity();
                    BeanUtils.copyProperties(commodity, newCommodity);
                    newCommodity.setStationId(station.getStationId());
                    newCommodity.setStationName(station.getStationName());
                    commodityList.add(newCommodity);
                }
            }

        } else if(UserConstants.LEVEL_THREE.equals(sysUser.getUserLevel())){
            Enterprise enterprise = enterpriseService.selectEnterpriseByStationId(sysUser.getStationId());
            commodity.setEnterpriseId(enterprise.getEnterpriseId());
            commodity.setEnterpriseName(enterprise.getEnterpriseName());
            Station station = stationService.selectStationById(sysUser.getStationId());
            commodity.setStationId(station.getStationId());
            commodity.setStationName(station.getStationName());
            commodityList.add(commodity);
        } else if(Objects.isNull(sysUser.getUserLevel()) || UserConstants.LEVEL_ONE.equals(sysUser.getUserLevel())){
            if(Objects.isNull(commodity.getStationId())){
                return AjaxResult.error("未选择仓库");
            }
            commodity.setEnterpriseId(-1L);
            commodity.setEnterpriseName("-");
            Repositories req = new Repositories();
            req.setStationId(commodity.getStationId());
            Repositories repository = repositoryService.selectOneRepository(req);
            commodity.setStationId(repository.getStationId());
            commodity.setStationName(repository.getStationName());
            commodityList.add(commodity);
        } else {
            return AjaxResult.error("该账号不能访问该页面");
        }
        commodityService.insertCommodity(commodityList);
        return AjaxResult.success();
    }

    /**
     * 编辑数据
     *
     * @param commodity 实体
     * @return 编辑结果
     */
    @PostMapping("/edit")
    @ApiOperation("编辑数据")
    public AjaxResult edit(@RequestBody Commodity commodity) {
        if(Objects.isNull(commodity) || Objects.isNull(commodity.getCommodityId())){
            return AjaxResult.error("请求参数异常");
        }
        if(Objects.isNull(commodity.getStationId())){
            return AjaxResult.error("请求选择门店或仓库");
        }
        int i = commodityService.update(commodity);
        if(i <= 0){
            return AjaxResult.error("编辑失败");
        }
        return AjaxResult.success();
    }

    /**
     * 删除数据
     *
     * @param ids 主键
     * @return 删除是否成功
     */
    @PostMapping("/delete")
    @ApiOperation("删除数据")
    public AjaxResult delete(@RequestBody List<Long> ids) {
        return AjaxResult.success(commodityService.delete(ids));
    }

    /**
     * 根据商品编码查询商品
     * */
    @PostMapping("/queryByCommodityCode")
    @ApiOperation("根据商品编码查询商品")
    public AjaxResult queryByCommodityCode(@RequestBody Commodity commodity) {
        if(Objects.isNull(commodity) || StringUtils.isEmpty(commodity.getCommodityCode())
                || Objects.isNull(commodity.getStationId())) {
            return AjaxResult.error("请求参数异常");
        }
        logger.info("queryByCommodityCode根据商品编码查询商品 请求参数 ：[{}]",JSONObject.toJSONString(commodity));
        Commodity result = commodityService.queryCommodity(commodity);
        logger.info("queryByCommodityCode根据商品编码查询商品 响应结果 ：[{}]",JSONObject.toJSONString(result));
        if(Objects.isNull(result)){
            return AjaxResult.error("商品不存在");
        }
        return AjaxResult.success(result);
    }

    /**
     * 根据商品条形码查询商品
     * */
    @PostMapping("/queryByBarCode")
    @ApiOperation("根据商品条形码查询商品")
    public AjaxResult queryByBarCode(@RequestBody Commodity commodity) {
        if(Objects.isNull(commodity) || StringUtils.isEmpty(commodity.getBarCode())
                || Objects.isNull(commodity.getStationId())) {
            return AjaxResult.error("请求参数异常");
        }
        logger.info("queryByBarCode根据商品条形码查询商品 请求参数 ：[{}]",JSONObject.toJSONString(commodity));
        Commodity result = commodityService.queryCommodity(commodity);
        logger.info("queryByBarCode根据商品条形码查询商品 响应结果 ：[{}]",JSONObject.toJSONString(result));
        if(Objects.isNull(result)){
            return AjaxResult.error("商品不不存在");
        }
        return AjaxResult.success(result);
    }

    /**
     * 批量导入商品下载模板
     * */
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) {
        try {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("template.xlsx", "UTF-8"));
            ExcelUtil<CommodityTemplate> excelUtil = new ExcelUtil<>(CommodityTemplate.class);
            excelUtil.init(Collections.emptyList(),"sheet1", Excel.Type.EXPORT);
            excelUtil.exportExcel(response.getOutputStream());
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
    }

    /**
     * 批量导入商品
     * */
    /**
     * 商品批量入库
     * */
    @PostMapping("/exportIn")
    @ApiOperation(value = "商品批量入库", httpMethod = "POST",response = CommodityExportErrorVo.class)
    public AjaxResult commodityExport(@RequestPart MultipartFile file){
        if (file == null || file.isEmpty()) {
            return AjaxResult.error("上传的文件不能为空");
        }
        List<CommodityTemplate> commodityList = new ArrayList<>();
        try {
            ExcelUtil<CommodityTemplate> util = new ExcelUtil<CommodityTemplate>(CommodityTemplate.class);
            commodityList = util.importExcel(file.getInputStream());
        } catch (Exception e){
            return AjaxResult.error("商品批量入库,文件上传失败");
        }
        List<CommodityExportErrorVo> commodityExportErrorVos = commodityService.exportAddWarehouseList(commodityList);

        if(CollectionUtils.isNotEmpty(commodityExportErrorVos)){
            return AjaxResult.error("存在批量入库失败商品",commodityExportErrorVos);
        }
        return AjaxResult.success();
    }
}

